`
https://leetcode.cn/problems/number-of-closed-islands/
`

/**
 * @param {number[][]} grid
 * @return {number}
 */
var closedIsland = function (grid) {
  let res = 0
  const m = grid.length, n = grid[0].length

  for (let j = 0; j < n; j++) {
    // 把靠上边的岛屿淹掉
    dfs(grid, 0, j)
    // 把靠下边的岛屿淹掉
    dfs(grid, m - 1, j)
  }
  for (let i = 0; i < m; i++) {
    // 把靠左边的岛屿淹掉
    dfs(grid, i, 0)
    // 把靠右边的岛屿淹掉
    dfs(grid, i, n - 1)
  }

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (grid[i][j] === 0) {
        // 找到一个岛，把岛淹没
        res++
        dfs(grid, i, j)
      }
    }
  }

  return res
};

function dfs(grid, i, j) {
  const m = grid.length, n = grid[0].length
  // 边界
  if (i < 0 || j < 0 || i >= m || j >= n) {
    return
  }

  // 已经是海
  if (grid[i][j] === 1) {
    return
  }

  grid[i][j] = 1

  dfs(grid, i + 1, j)
  dfs(grid, i - 1, j)
  dfs(grid, i, j + 1)
  dfs(grid, i, j - 1)
}